import React, { useState, useEffect, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { FormInstance } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import TableHint from '@/components/TableHint/Index';
import StatisticsCard from '@/components/StatisticsCard/Index';
import { ProFormFieldSet } from '@ant-design/pro-form';
import { Button, DatePicker, Pagination } from 'antd';
import BreadcrumbDept from '@/components/BreadcrumbDept';
import { history } from 'umi';
import moment from 'moment';
import { getGoodsSaleDataForDetail, downGoodsSaleDataForDetail } from '@/services/report/api'; 
import { isNull, showMsg } from '@/utils/utils';
import './style.less'
import PermissionControl from '@/components/PermissionControl';
import MyPagination from '@/components/MyPagination';

const Index: React.FC = (props) => {
  const { id = '', title = '', start, end } = props.location.query;
  const formRef = useRef<FormInstance>();
  const actionRef = useRef<ActionType>();
  const [detail, setDetail] = useState({});
  const [loading, setLoading] = useState<boolean>(false);
  const [searchParams, setSearchParams] = useState({});
  const [current, setCurrent] = useState(1); // 当前页
  const [total, setTotal] = useState(20); // 总记录数

  // 合并行
  const hb = (value: any, record: any, index: number, key) => {
    const obj: any = {
      children: value,
      props: {},
    };
    if (index > 0) {
      const before = detail.record_list[index - 1]; // 前一行
      if (before?.goodsId === record.goodsId && before[key] === record[key]) {
        // 与前一行相同，那当前就是被合并的行
        obj.props.rowSpan = 0;
        return obj;
      }
    }
    // 计算需要合并多少行
    const afterDataArr = detail.record_list.slice(index + 1);
    let count = 0;
    for (let i = 0, len = afterDataArr.length; i < len; i++) {
      const tmp = afterDataArr[i];
      if (tmp.goodsId === record.goodsId && tmp[key] === record[key]) {
        count += 1;
      } else {
        break;
      }
    }
    if (count === 0) {
      return obj;
    }
    obj.props.rowSpan = count + 1;
    return obj;
  }
 
  const columns: ProColumns<any>[] = [
    {
      title: '商品编号',
      dataIndex: 'goodsId',
      width: 120,
      fieldProps: {
        placeholder: '完整商品编号',
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项'
          }
        ]
      },
      render: (value, record, index) => hb(value, record, index, 'goodsId')
    },
    {
      title: '商品名称',
      dataIndex: 'goodsName',
      width: 150,
      fieldProps: {
        placeholder: '拼音首字母/文字',
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项'
          }
        ]
      },
      render: (value, record, index) => hb(value, record, index, 'goodsName')
    },
    {
      title: '统计周期',
      dataIndex: 'rangedate',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest },form) => {
        if (type === 'form') {
          return null;
        }
        return (<ProFormFieldSet style={{gap: 2}}>
            <DatePicker allowClear={false} style={{width: '100%'}} />
              <span style={{padding: '0 5px'}}>-</span>
            <DatePicker  allowClear={false} style={{width: '100%'}} />
          </ProFormFieldSet>
        );
      }
    },
    {
      title: '规格',
      dataIndex: 'specsName',
      width: 150,
      search: false,
      render: (value, record, index) => hb(value, record, index, 'specsName')
    },
    {
      title: '数量',
      dataIndex: 'goodsNum',
      align: 'right',
      search: false,
      width: 100
    },

    {
      title: '金额',
      dataIndex: 'goodsTotalPrice',
      align: 'right',
      valueType: 'money',
      search: false,
      width: 100
    },

    {
      title: '订单号',
      dataIndex: 'orderId',
      search: false,
      width: 160
    },
   
    {
      title: '结算单号',
      dataIndex: 'settleNo',
      search: false,
      width: 160
    },

    {
      title: '交易渠道',
      dataIndex: 'orderType',
      search: false,
      width: 95,
      valueEnum: {
        P: '计划订单',
        O: '一次性订单',
        R: '租赁订单', 
        S: '小程序',
      }
    },

    {
      title: '业务方向',
      dataIndex: 'goodsType',
      search: false,
      width: 80,
      valueEnum: {
        P: '交易',
        R: '退款', 
      }
    },
    
    {
      title: '业务发生时间',
      dataIndex: 'tradeTime',
      search: false,
      width: 180
    },
    {
      title: '商品状态',
      dataIndex: 'inventoryStatus',
      search: false,
      width: 80
    }
  ];

  useEffect(() => {
    formRef.current?.setFieldsValue({
      rangedate: [moment(start), '-', moment(end)],
      goodsId: id,
      goodsName: title,
    });
    formRef.current?.submit();
  }, [])

  // 翻页
  const onChange = (page) => {
    setCurrent(page)
    actionRef.current.reload();
  }

  const getList = async(params: any) => {
    try {
      params.begin_date_str = moment(params.rangedate[0]).format('YYYYMMDD');
      params.end_date_str = moment(params.rangedate[2]).format('YYYYMMDD');
      params.current = current;
      params.pageSize = 20;
      const data = await getGoodsSaleDataForDetail(params);
      setDetail(data);
      setSearchParams(params);
      if (current === 1) {
        setTotal(data.sum_record_num)
      }
      return {
        data: data.record_list,
        success: true,
        total: data.sum_record_num
      }
    } catch (error) {
      showMsg(error?.data?.errmsg); 
      return {
        data: [],
        success: true,
        total: 0
      };
    }
  }

  const download = async() => {
    setLoading(true);
    await downGoodsSaleDataForDetail(searchParams).then(res => {
      setLoading(false);
      window.open(`/api/report/${res.file_token}/down`);
    }).catch(res => {
      setLoading(false);
    });
  }

  return (
    <PageContainer
      extra={[<BreadcrumbDept />]}
      title="商品销售明细"
      breadcrumb={{}}
      onBack={() => history.goBack()}
    >
      <ProTable<any, COMMON.PageParams>
        actionRef={actionRef}
        formRef={formRef}
        rowKey="goods_id"
        bordered
        manualRequest
        form={{
          ignoreRules: false,
        }}
        search={{
          defaultCollapsed: false,
          collapseRender: () => {
            return '';
          },
          optionRender: (searchConfig, formProps, dom) => {
            dom.shift();
            return [
              ...dom,
              <PermissionControl action_id="700700004">
                <Button
                  key="export"
                  type="primary"
                  disabled={isNull(detail.record_list)}
                  loading={loading}
                  onClick={download}
                >
                  导出报表
                </Button>
              </PermissionControl>,
            ];
          },
        }}
        request={getList}
        scroll={{ x: 1200 }}
        columns={columns}
        options={false}
        tableExtraRender={(_, data) => (
          <div className="StatisticsCard" style={{ background: '#fff', padding: 12 }}>
            <div
              style={{
                marginBottom: 0,
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
              }}
            >
              <StatisticsCard
                iconType="database"
                title="周期商品销售数量"
                number={detail.totalPGoodsNum}
              />
              <StatisticsCard title="周期商品销售总额" number={`￥${detail.totalPPrice}`} />
              <StatisticsCard
                iconType="database"
                title="周期商品退款数量"
                number={detail.totalRGoodsNum}
              />
              <StatisticsCard
                style={{ marginRight: 0 }}
                title="周期商品退款总额"
                number={`￥${detail.totalRPrice}`}
              />
            </div>

            <TableHint text="商品销售受折扣影响，销售额为系统计算后的四舍五入值，请勿将此表格统计金额用于销售对账。" />
          </div>
        )}
        pagination={false}
        // 搜索前把分页重置
        beforeSearchSubmit={(e) => {
          setCurrent(1);
          return e;
        }}
      />
      <MyPagination
        current={current}
        pageSize={20}
        onChange={onChange}
        total={total}
      />
    </PageContainer>
  );
};
export default Index;
